﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace Util.IO
{
    // V 1.0.0 - 2024-09-25 14:54:30
    // 模拟鼠标移动和点击操作

    /// <summary>
    /// MouseUtils
    /// </summary>
    public class MouseUtils
    {
        /// <summary>
        /// The MOUSEINPUT structure contains information about a simulated mouse event. (see: http://msdn.microsoft.com/en-us/library/ms646273(VS.85).aspx)
        /// Declared in Winuser.h, include Windows.h
        /// </summary>
        /// <remarks>
        /// If the mouse has moved, indicated by MOUSEEVENTF_MOVE, dx and dy specify information about that movement. The information is specified as absolute or relative integer values. 
        /// If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535. The event procedure maps these coordinates onto the display surface. Coordinate (0,0) maps onto the upper-left corner of the display surface; coordinate (65535,65535) maps onto the lower-right corner. In a multimonitor system, the coordinates map to the primary monitor. 
        /// Windows 2000/XP: If MOUSEEVENTF_VIRTUALDESK is specified, the coordinates map to the entire virtual desktop.
        /// If the MOUSEEVENTF_ABSOLUTE value is not specified, dx and dy specify movement relative to the previous mouse event (the last reported position). Positive values mean the mouse moved right (or down); negative values mean the mouse moved left (or up). 
        /// Relative mouse motion is subject to the effects of the mouse speed and the two-mouse threshold values. A user sets these three values with the Pointer Speed slider of the Control Panel's Mouse Properties sheet. You can obtain and set these values using the SystemParametersInfo function. 
        /// The system applies two tests to the specified relative mouse movement. If the specified distance along either the x or y axis is greater than the first mouse threshold value, and the mouse speed is not zero, the system doubles the distance. If the specified distance along either the x or y axis is greater than the second mouse threshold value, and the mouse speed is equal to two, the system doubles the distance that resulted from applying the first threshold test. It is thus possible for the system to multiply specified relative mouse movement along the x or y axis by up to four times.
        /// </remarks>
        [StructLayout(LayoutKind.Sequential)]
        struct MOUSEINPUT
        {
            /// <summary>
            /// Specifies the absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member. Absolute data is specified as the x coordinate of the mouse; relative data is specified as the number of pixels moved.
            /// </summary>
            public int X;

            /// <summary>
            /// Specifies the absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member. Absolute data is specified as the y coordinate of the mouse; relative data is specified as the number of pixels moved. 
            /// </summary>
            public int Y;

            /// <summary>
            /// If dwFlags contains MOUSEEVENTF_WHEEL, then mouseData specifies the amount of wheel movement. A positive value indicates that the wheel was rotated forward, away from the user; a negative value indicates that the wheel was rotated backward, toward the user. One wheel click is defined as WHEEL_DELTA, which is 120. 
            /// Windows Vista: If dwFlags contains MOUSEEVENTF_HWHEEL, then dwData specifies the amount of wheel movement. A positive value indicates that the wheel was rotated to the right; a negative value indicates that the wheel was rotated to the left. One wheel click is defined as WHEEL_DELTA, which is 120.
            /// Windows 2000/XP: IfdwFlags does not contain MOUSEEVENTF_WHEEL, MOUSEEVENTF_XDOWN, or MOUSEEVENTF_XUP, then mouseData should be zero. 
            /// If dwFlags contains MOUSEEVENTF_XDOWN or MOUSEEVENTF_XUP, then mouseData specifies which X buttons were pressed or released. This value may be any combination of the following flags. 
            /// </summary>
            public uint MouseData;

            /// <summary>
            /// A set of bit flags that specify various aspects of mouse motion and button clicks. The bits in this member can be any reasonable combination of the following values. 
            /// The bit flags that specify mouse button status are set to indicate changes in status, not ongoing conditions. For example, if the left mouse button is pressed and held down, MOUSEEVENTF_LEFTDOWN is set when the left button is first pressed, but not for subsequent motions. Similarly, MOUSEEVENTF_LEFTUP is set only when the button is first released. 
            /// You cannot specify both the MOUSEEVENTF_WHEEL flag and either MOUSEEVENTF_XDOWN or MOUSEEVENTF_XUP flags simultaneously in the dwFlags parameter, because they both require use of the mouseData field. 
            /// </summary>
            public uint Flags;

            /// <summary>
            /// Time stamp for the event, in milliseconds. If this parameter is 0, the system will provide its own time stamp. 
            /// </summary>
            public uint Time;

            /// <summary>
            /// Time stamp for the event, in milliseconds. If this parameter is 0, the system will provide its own time stamp. 
            /// </summary>
            public IntPtr ExtraInfo;
        }

        /// <summary>
        /// The combined/overlayed structure that includes Mouse, Keyboard and Hardware Input message data (see: http://msdn.microsoft.com/en-us/library/ms646270(VS.85).aspx)
        /// </summary>
        [StructLayout(LayoutKind.Explicit)]
        struct InputUnion
        {
            /// <summary>
            /// The <see cref="T:WindowsInput.Native.MOUSEINPUT" /> definition.
            /// </summary>
            [FieldOffset(0)]
            public MOUSEINPUT MouseInput;
        }

        /// <summary>
        /// The INPUT structure is used by SendInput to store information for synthesizing input events such as keystrokes, mouse movement, and mouse clicks. (see: http://msdn.microsoft.com/en-us/library/ms646270(VS.85).aspx)
        /// Declared in Winuser.h, include Windows.h
        /// </summary>
        /// <remarks>
        /// This structure contains information identical to that used in the parameter list of the keybd_event or mouse_event function.
        /// Windows 2000/XP: INPUT_KEYBOARD supports nonkeyboard input methods, such as handwriting recognition or voice recognition, as if it were text input by using the KEYEVENTF_UNICODE flag. For more information, see the remarks section of KEYBDINPUT.
        /// </remarks>        
        [StructLayout(LayoutKind.Sequential)]
        struct INPUT
        {
            public int Type;
            public InputUnion Data;
        }

        /// <summary>
        /// The set of MouseFlags for use in the Flags property of the <see cref="T:WindowsInput.Native.MOUSEINPUT" /> structure. (See: http://msdn.microsoft.com/en-us/library/ms646273(VS.85).aspx)
        /// </summary>
        [Flags]
        public enum MouseEventFlags : uint
        {
            /// <summary>
            /// Specifies that movement occurred.
            /// </summary>
            MOVE = 1U,
            /// <summary>
            /// Specifies that the left button was pressed.
            /// </summary>
            LEFTDOWN = 2U,
            /// <summary>
            /// Specifies that the left button was released.
            /// </summary>
            LEFTUP = 4U,
            /// <summary>
            /// Specifies that the right button was pressed.
            /// </summary>
            RIGHTDOWN = 8U,
            /// <summary>
            /// Specifies that the right button was released.
            /// </summary>
            // RIGHTUP = 0x0010,
            RIGHTUP = 16U,
            /// <summary>
            /// Specifies that the middle button was pressed.
            /// </summary>
            // MIDDLEDOWN = 0x0020,
            MIDDLEDOWN = 32U,
            /// <summary>
            /// Specifies that the middle button was released.
            /// </summary>
            // MIDDLEUP = 0x0040,
            MIDDLEUP = 64U,
            /// <summary>
            /// Specifies that the dx and dy members contain normalized absolute coordinates. If the flag is not set, dxand dy contain relative data (the change in position since the last reported position). This flag can be set, or not set, regardless of what kind of mouse or other pointing device, if any, is connected to the system. For further information about relative mouse motion, see the following Remarks section.
            /// </summary>
            // ABSOLUTE = 0x8000,
            ABSOLUTE = 32768U,


            /// <summary>
            /// Windows 2000/XP: Specifies that an X button was pressed.
            /// </summary>
            // Token: 0x04000029 RID: 41
            XDown = 128U,
            /// <summary>
            /// Windows 2000/XP: Specifies that an X button was released.
            /// </summary>
            // Token: 0x0400002A RID: 42
            XUp = 256U,
            /// <summary>
            /// Windows NT/2000/XP: Specifies that the wheel was moved, if the mouse has a wheel. The amount of movement is specified in mouseData. 
            /// </summary>
            // Token: 0x0400002B RID: 43
            VerticalWheel = 2048U,
            /// <summary>
            /// Specifies that the wheel was moved horizontally, if the mouse has a wheel. The amount of movement is specified in mouseData. Windows 2000/XP:  Not supported.
            /// </summary>
            // Token: 0x0400002C RID: 44
            HorizontalWheel = 4096U,
            /// <summary>
            /// Windows 2000/XP: Maps coordinates to the entire desktop. Must be used with MOUSEEVENTF_ABSOLUTE.
            /// </summary>
            // Token: 0x0400002D RID: 45
            VirtualDesk = 16384U,
        }

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern bool SetCursorPos(int X, int Y);

        [DllImport("user32.dll", SetLastError = true)]
        static extern uint SendInput(uint nInputs, ref INPUT pInputs, int cbSize);

        static void MouseEventHandler(MouseEventFlags dwFlags)
        {
            INPUT ip = new INPUT();
            ip.Type = 0; // 0 -- 鼠标
            //ip.Data.MouseInput.X = x; // 没起作用
            //ip.Data.MouseInput.Y = y; // 没起作用
            ip.Data.MouseInput.Flags = (uint)dwFlags;
            ip.Data.MouseInput.Time = 0U;
            ip.Data.MouseInput.ExtraInfo = IntPtr.Zero;

            SendInput(1, ref ip, Marshal.SizeOf(ip));
        }

        /// <summary>
        /// /// 发送鼠标操作 ( 点击 )
        /// </summary>
        /// <param name="dwFlags"></param>
        public static void Send(MouseEventFlags dwFlags)
        {
            MouseEventHandler(dwFlags); // 发送鼠标按钮按下事件
        }

        /// <summary>
        /// 发送鼠标操作 ( 移动 )
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public static void Send(int x, int y)
        {
            SetCursorPos(x, y); // 模拟鼠标移动到指定位置
        }

        /// <summary>
        /// 发送鼠标操作 ( 点击与移动 )
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="dwFlags"></param>
        public static void Send(int x, int y, MouseEventFlags dwFlags)
        {
            SetCursorPos(x, y); // 模拟鼠标移动到指定位置
            MouseEventHandler(dwFlags); // 发送鼠标按钮按下事件
        }
    }
}
